﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/


// #define GOOGLEANALYTICS
// DEFINE THIS IF YOU WANT GOOGLE ANALYTIC MONITORING

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using Graphs;
using System.IO;
using System.Windows.Browser;

namespace ConceptLink
{
    /// <summary>
    /// Main page.
    /// </summary>
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            SearchCanvas.NodeClicked+=new GraphCanvas.NodeEvent(SearchCanvas_NodeClicked);
            SearchCanvas.NodeHover+=new GraphCanvas.NodeEvent(SearchCanvas_NodeHover);
            SearchCanvas.NodeLeave+=new GraphCanvas.NodeEvent(SearchCanvas_NodeLeave);
            ParetoCanvas.NodeHover += new Pareto.NodeEvent(ParetoCanvas_NodeHover);
            ParetoCanvas.NodeLeave += new Pareto.NodeEvent(ParetoCanvas_NodeLeave);

#if GOOGLEANALYTICS
            try
            {
                HtmlPage.Window.Invoke(
                    "trackEvent",
                    new object[] {
                    "clink",
                    "loaded"
                }
                );
            }
            catch
            {
            }
#endif
        }


        private void Go_Click(object sender, RoutedEventArgs e)
        {
#if GOOGLEANALYTICS
            try
            {
                HtmlPage.Window.Invoke(
                    "trackEvent",
                    new object[] {
                    "clink",
                    "search",                    
                    From.Selected.title + " TO " + To.Selected.title
                }
                );
            }
            catch
            {
            }
#endif
            // user requested a search

            SearchStartTime = DateTime.Now;

            SearchCanvas.Clear();

            Main.Visibility = Visibility.Collapsed;
            SearchTitle.Text = ButtonText.Text;
            
           
            // create a 1way search
            sc = new SearchContext1Way(From.Selected, To.Selected, SearchCanvas.graph);
            sc.ColorFromStart = true;
            sc.ColorCurrentPath = true;
            
            // perform the first step
            SearchStep(sc);
            SearchPanel.Visibility = Visibility.Visible;
        }

        Timer t;
        DateTime SearchStartTime;

        /// <summary>
        /// wait a bit, then perform a search step if not complete.
        /// </summary>
        /// <param name="sc">the searhc context to use</param>
        private void SearchStep(SearchContext sc)
        {
            if (sc.Path != null)
            {
                // Zoom to the current path if we have one
                SearchCanvas.ZoomToView = (from c in sc.Path select SearchCanvas.graph.GetNode(c.title)).ToArray();
            }

            // wait a bit
            t = new Timer(delegate
                {
                    t.Dispose();

                    if (sc == this.sc && !sc.Compelete)
                    {
                        // perform a step
                        sc.Step(SearchStep);
                    }
                    else
                    {
                        // search compelte, show expand button

                        ExpandButton.Dispatcher.BeginInvoke(() =>
                            {
                                ExpandButton.Visibility = Visibility.Visible;

#if GOOGLEANALYTICS
                                try
                                {
                                    HtmlPage.Window.Invoke(
                                        "trackEvent",
                                        new object[] {
                    "clink",
                    "searchsteps",                    
                    From.Selected.title + " TO " + To.Selected.title,
                    sc.Path.Length
                }
                                    );

                                    HtmlPage.Window.Invoke(
                                        "trackEvent",
                                        new object[] {
                    "clink",
                    "nodesclosed",                    
                    From.Selected.title + " TO " + To.Selected.title,
                    (sc as SearchContext1Way).closed.Count

                }
                                    );

                                    HtmlPage.Window.Invoke(
                                        "trackEvent",
                                        new object[] {
                    "clink",
                    "nodesopen",                    
                    From.Selected.title + " TO " + To.Selected.title,
                    (sc as SearchContext1Way).open.Count

                }
                                    );


                                    HtmlPage.Window.Invoke(
                                        "trackEvent",
                                        new object[] {
                    "clink",
                    "timetaken",                    
                    From.Selected.title + " TO " + To.Selected.title,
                    (int)((DateTime.Now - SearchStartTime).TotalSeconds)
                }
                                    );
                                }
                                catch
                                {
                                }
#endif
                            });
                    }
                }, null, 2000, System.Threading.Timeout.Infinite);
        }

        /// <summary>
        /// current search context
        /// </summary>
        SearchContext sc;

        
        void Changed(ConceptSelector sender, Search.SearchResult item)
        {
            // called when a concept is selected

            if (To.Selected != null && From.Selected != null)
            {
                // if we have selected 2 concepts, get their relatedness, then show the button

                Relatedness.Get(From.Selected.title, To.Selected.title,
                    delegate(string a1, string a2, float rel)
                    {
                        ButtonText.Text = "Link '" + a1 + "' to '" + a2 + "' (" + rel.ToString("0.0%") + " related)";
                        Go.Visibility = Visibility.Visible;
                    });
            }
            else
            {
                Go.Visibility = Visibility.Collapsed;
            }
        }

        private void Back_Click(object sender, RoutedEventArgs e)
        {
            // new search clicked. reload the page

            Main.Visibility = Visibility.Collapsed;
            SearchPanel.Visibility = Visibility.Collapsed;

            Go.Visibility = Visibility.Collapsed;

            HtmlPage.Document.Submit();             
        }


        #region searchcanvas events

        Node centered = null;
        
        void SearchCanvas_NodeClicked(GraphCanvas sender, Node n)
        {
            if (n == centered)
            {
                SearchCanvas.ZoomToView = null;
            }
            else
            {
                centered = n;
                List<Node> view = new List<Node>(sc.Graph.GetNodesLinkedToNode(n));
                view.Add(n);
                SearchCanvas.ZoomToView = view.ToArray();
            }
        }

        void SearchCanvas_NodeLeave(GraphCanvas sender, Node n)
        {
            InfoPanel.Visibility = Visibility.Collapsed;
        }

        void SearchCanvas_NodeHover(GraphCanvas sender, Node n)
        {
            LoadNodeInfo(InfoPanel, n);
        }
        #endregion

        #region paretocanvas events
        void ParetoCanvas_NodeLeave(Pareto sender, Node n)
        {
            InfoPanelPareto.Visibility = Visibility.Collapsed;
            ParetoCanvas.ResetView();
        }

        Node LoadingPareto = null;
        void ParetoCanvas_NodeHover(Pareto sender, Node node)
        {
            
            LoadingPareto = node;

            LoadNodeInfo(InfoPanelPareto, node);

            ParetoCanvas.HideLabels();
            ParetoCanvas.ShowLabel(node);

            node.color = Colors.Blue;
            node.node_radius = 20;
            node.UpdateUIElemet();

            Links.Get(node.id, true, true, -1, delegate(int id, Links.LinksResult[] outs, Links.LinksResult[] ins)
            {
                if (LoadingPareto != node) // another request was made while loading this one
                    return;

                foreach (var n in outs)
                {
                    Node np = ParetoCanvas.Nodes.FirstOrDefault(npnode => npnode.text == n.title);
                    if (np != null)
                    {
                        np.color = Colors.Green;
                        ParetoCanvas.ShowLabel(np);
                        ParetoCanvas.BringToTop(np);
                        np.UpdateUIElemet();
                    }
                }

                foreach (var n in ins)
                {
                    Node np = ParetoCanvas.Nodes.FirstOrDefault(npnode => npnode.text == n.title);
                    if (np != null)
                    {
                        if (np.color == Colors.Green)
                            np.color = Colors.Yellow;
                        else
                            np.color = Colors.Red;

                        ParetoCanvas.ShowLabel(np);
                        ParetoCanvas.BringToTop(np);
                        np.UpdateUIElemet();
                    }
                }
            });

        }
        #endregion

        // adds some information about a wikivisnode to a uielement.
        private void LoadNodeInfo(UIElement uIElement, Node n)
        {
            
            var stack = new StackPanel();
            
            uIElement.Visibility = Visibility.Visible;
            (uIElement as Border).Child = stack;

            stack.Children.Add(new TextBox() { Text = n.text, FontSize = 16 });

            TextBox t = new TextBox() { MaxWidth = SearchCanvas.ActualWidth / 3, TextWrapping = TextWrapping.Wrap, FontSize = 12 };
            stack.Children.Add(t);
            Search.Get(n.id, delegate(string a1, Search.SearchResult[] results)
            {
                if (results != null && results.Length > 0)
                    t.Text = results[0].description;
            });


            TextBox t_info = new TextBox() { MaxWidth = SearchCanvas.ActualWidth / 3, TextWrapping = TextWrapping.Wrap, FontSize = 12 };
            
            stack.Children.Add(t_info);


            if (n is WikiVisNode)
            {
                t_info.Text += (t_info.Text != "" ? "\r\n" : "") + "Distance from '" + From.Selected.title + "': " + (n as WikiVisNode).g.ToString("0.0");
                t_info.Text += (t_info.Text != "" ? "\r\n" : "") + "Optimistic Estimate to '" + To.Selected.title + "': " + (n as WikiVisNode).h.ToString("0.0");
            }
            

            Relatedness.Get(sc.From.title, n.text, delegate(string a1, string a2, float rel)
            {
                t_info.Text += (t_info.Text != "" ? "\r\n" : "") + "Relatedness to '" + From.Selected.title + "': " + rel.ToString("0.0%");
            });
            Relatedness.Get(sc.To.title, n.text, delegate(string a1, string a2, float rel)
            {
                t_info.Text += (t_info.Text != "" ? "\r\n" : "") + "Relatedness to '" + To.Selected.title + "': " + rel.ToString("0.0%");
            });

        }


        private bool Expanding = false;
        private void Expand_Click(object sender, RoutedEventArgs e)
        {
            ExpandButton.Visibility = Visibility.Collapsed;
            StopExpandButton.Visibility = Visibility.Visible;
            Expanding = true;
            sc.Step(ExpandingDone);
        }
        private void Expand2_Click(object sender, RoutedEventArgs e)
        {
            StopExpandButton.Visibility = Visibility.Collapsed;
            Expanding = false;
        }


        private void ExpandingDone(SearchContext sc)
        {
            if (sc.Path != null)
                SearchCanvas.ZoomToView = (from c in sc.Path select SearchCanvas.graph.GetNode(c.title)).ToArray();

            if (!Expanding)
            {
                ExpandButton.Dispatcher.BeginInvoke(() => ExpandButton.Visibility = Visibility.Visible);
            }
            else
            {
                t = new Timer(delegate
                {
                    t.Dispose();

                    if (!Expanding)
                    {
                        ExpandButton.Dispatcher.BeginInvoke(() => ExpandButton.Visibility = Visibility.Visible);
                    }
                    else
                    {
                        sc.Step(ExpandingDone);
                    }                    
                }, null, 2000, System.Threading.Timeout.Infinite);
                
            }
            
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.DefaultExt = "cxl";

            sfd.Filter = "CXL Files|*.cxl";
            sfd.FilterIndex = 1;

            var result = sfd.ShowDialog();

            // create a CXL file
            if (result.HasValue && result.Value == true)
            {
                var stream = sfd.OpenFile();
                var writer = new StreamWriter(stream);

                writer.Write(
@"<?xml version=""1.0"" encoding=""UTF-8""?>
<cmap xmlns=""http://cmap.ihmc.us/xml/cmap/""
      xmlns:dc=""http://purl.org/dc/elements/1.1/"">
    <map>
        <concept-list>
");
                var nodes = sc.Graph.GetNodes();

                float minx = float.MaxValue;
                float miny = float.MaxValue;

                
                float maxx = float.MinValue;
                float maxy = float.MinValue;


                var links = sc.Graph.GetLinks();

                foreach (var n in nodes)
                {
                    if (n.visible)
                    {
                        writer.Write(@"<concept id=""" + n.id + @""" label=""" + n.text + @""" />
");
                        if (n.x < minx) minx = n.x;
                        if (n.y < miny) miny = n.y;
                        if (n.x > maxx) maxx = n.x;
                        if (n.y > maxy) maxy = n.y;
                    }
                }


                miny -= 100;
                minx -= 100;
                maxy += 100;
                maxx += 100;


              writer.Write(
@"        </concept-list>
        <connection-list>
");

              foreach (var l in links)
              {
                  if (l.visible && l.a.visible && l.b.visible)
                      if (l.arrow_on_b)
                      {
                          writer.Write(@"<connection 
from-id=""" + l.a.id + @""" to-id=""" + l.b.id + @""" 
isBidirectional=""" + (l.arrow_on_a ? "true" : "false") + @""" />
");
                      }
                      else if (l.arrow_on_a)
                      {
                          writer.Write(@"<connection 
from-id=""" + l.b.id + @""" to-id=""" + l.a.id + @""" />
");
                      }


                
              }

              writer.Write(@"
        </connection-list>
        <concept-appearance-list>
");

              foreach (var n in nodes)
              {
                  if (n.visible)
                      writer.Write(@"<concept-appearance id=""" + n.id + @""" 
x=""" + (int)(n.x - minx ) + @""" y=""" + (int)(n.y -miny) + @""" 
background-color=""" + n.color.R + @"," + n.color.G + @"," + n.color.B + @"," + n.color.A + @""" 
width=""" + (int)(n.node_radius * 2) + @""" height=""" + (int)(n.node_radius * 2) + @""" 

border-shape=""oval""
/>
");
                   
              }
              writer.Write(
@"
        </concept-appearance-list>
    </map>
</cmap>
");

              writer.Flush();
              stream.Close();            

            }
        }

        // show a pareto plot
        private void Plot_Click(object sender, RoutedEventArgs e)
        {
#if GOOGLEANALYTICS
            try
            {
                HtmlPage.Window.Invoke(
                    "trackEvent",
                    new object[] {
                    "clink",
                    "plot",                    
                    From.Selected.title + " TO " + To.Selected.title
                }
                );
            }
            catch
            {
            }
#endif

            SearchPanel.Visibility = Visibility.Collapsed;
            ParetoPanel.Visibility = Visibility.Visible;

            // only one way right now
            var sc = this.sc as SearchContext1Way;

            ParetoCanvas.Show(From.Selected, To.Selected, 
                sc.closed.Union(from a in sc.open select a.article).ToArray()
                );    
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            SearchPanel.Visibility = Visibility.Visible;
            ParetoPanel.Visibility = Visibility.Collapsed;            
        }            
    }
}
